package com.fingard.dsp.bank.directbank.yeepay02;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.yeepay.g3.sdk.yop.client.YopRequest;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class YEEPAY02Base extends DirectBase {

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    protected YopRequest getYoprequest(Map<String, String> params, ActSetItem actItem) {
        Set<Map.Entry<String, String>> entry = params.entrySet();
        YopRequest yoprequest = new YopRequest(actItem.merchantId, actItem.ownKeyStorePath);
        for (Map.Entry<String, String> s : entry) {
            yoprequest.addParam(s.getKey(), s.getValue());
        }

        return yoprequest;
    }

    //将获取到的response转换成json格式
    public static Map<String, Object> parseResponse(String yopresponse) {

        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap = JSON.parseObject(yopresponse,
                new TypeReference<TreeMap<String, Object>>() {
                });
        System.out.println("将response转化为map格式之后: " + jsonMap);
        return jsonMap;
    }

    /**
     * 将MAP转换为post请求串
     * @return
     */
    public String convertMapToStr(Map<String,Object> params) {
        String reqStr = "";
        for (String key : params.keySet()) {
            if (!params.get(key).equals("")) {
                if (reqStr.length() > 0) {
                    reqStr += "&";
                }
                reqStr += key + "=" + params.get(key);
            }
        }
        return reqStr;
    }

    /**
     * 发送报文至银行
     * @param p_reqStr 请求报文
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr, String url) throws Exception {
        String[] retStr = new String[]{"", ""};

        WriteBankLogLn("1.提交银行的地址：" + url);
        int n = p_reqStr.getBytes("UTF-8").length;
        //String p_head = decimalFormat.format(n);
        String p_string = p_reqStr;
        WriteBankLogStep2(p_string);
        WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/json");
        tmpWebRequest.setRequestProperty("connection", "Close");
        byte[] tmpToWriteBytes = p_string.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpToWriteBytes, getCharset());
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

}
